//
//  LSYBookManager.m
//  LSYReader
//
//  Created by sam on 2018/3/27.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "LSYFileUtil.h"
#import "LSYBookManager.h"
#import "LSYNovelService.h"

#define kBookKey @"kBookKey"

@implementation LSYBookManager
+ (instancetype)manager {
    static LSYBookManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LSYBookManager alloc] init];
        manager.books = [manager recoverFromFile];
    });
    return manager;
}

- (void)addNetBook:(LSYBook *)book {
    LSYReadModel *model = [[LSYReadModel alloc] initWithNetBook:book];
    [self addBook:model];
}

- (void)addBook:(LSYReadModel *)book {
    for (LSYReadModel *model in self.books) {
        if ([model isEqual:book]) {
            model.chapters = book.chapters;
            model.netBook.chapters = book.netBook.chapters;
            [self saveToFile];
            return;
        }
    }
    [self.books addObject:book];
    [self saveToFile];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kBookManagerRefresBooksNoti object:nil];
    });
}

- (void)removeBook:(LSYReadModel *)book {
    
    [LSYFileUtil removePath:[LSYFileUtil absolutePath:book.resourcePath]];
    LSYReadModel *model = nil;
    for (LSYReadModel *b in self.books) {
        if ([b.resourcePath isEqualToString:book.resourcePath]) {
            model = b;
            break;
        }
    }
    [self.books removeObject:model];;
    [self saveToFile];
    [[NSNotificationCenter defaultCenter] postNotificationName:kBookManagerRefresBooksNoti object:nil];
}

- (BOOL)existBook:(LSYReadModel *)book {
    for (LSYReadModel *model in self.books) {
        if ([model isEqual:book]) {
            return YES;
        }
    }
    return NO;
}

- (void)refreshBook:(LSYReadModel *)book {
    [LSYNovelService getChapters:book.netBook block:^(NSArray *chapters) {
        if (book.netBook.chapters.count>chapters.count) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self addBook:book];
            });
        }
    }];
}

- (void)saveToFile {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (![NSKeyedArchiver archiveRootObject:self.books toFile:[LSYFileUtil bookStorePath]]){
            [NSKeyedArchiver archiveRootObject:self.books toFile:[LSYFileUtil bookStorePath]];
        }
    });
}

- (NSMutableArray *)recoverFromFile {
    NSArray *books = [NSKeyedUnarchiver unarchiveObjectWithFile:[LSYFileUtil bookStorePath]];
    if (books && [books isKindOfClass:[NSArray class]]) {
        return [NSMutableArray arrayWithArray:books];
    }
    return [NSMutableArray array];
}
@end
